package coin.yang.meituan;

import java.util.Arrays;

/**
 * @author coinyang
 * @date 2023/10/12 17:51
 */
public class NO1 {
    /*
    两个数组合并成一个并排序。例:a[1,2,3];b[2,5,6]
     */
    public static int[] mergeAndSort(int[] a, int[] b) {
        int[] merged = new int[a.length + b.length];
        System.arraycopy(a, 0, merged, 0, a.length);
        System.arraycopy(b, 0, merged, a.length, b.length);
        Arrays.sort(merged);
        return merged;
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = {2, 5, 6};

        int[] merged = mergeAndSort(a, b);
        System.out.println(Arrays.toString(merged));
    }


    public static int[] mergeAndSort2(int[] a, int[] b) {
        int[] merged = new int[a.length + b.length];
        int i = 0;  // a数组的指针
        int j = 0;  // b数组的指针
        int k = 0;  // merged数组的指针

        while (i < a.length && j < b.length) {
            if (a[i] <= b[j]) {
                merged[k] = a[i];
                i++;
            } else {
                merged[k] = b[j];
                j++;
            }
            k++;
        }

        // 将剩余的元素添加到merged数组中
        while (i < a.length) {
            merged[k] = a[i];
            i++;
            k++;
        }

        while (j < b.length) {
            merged[k] = b[j];
            j++;
            k++;
        }

        return merged;
    }
}
